import React from 'react';
import UploadComponent from './index';
import { Upload, Icon, message } from 'antd';
import Cropper from 'react-cropper';
import Modal from '../Modal';
import services from '../../services/api';

import { APIUrl } from '../../services/createServices';
import 'cropperjs/dist/cropper.css';
import './previewImg.less';

class PreviewUploadComponent extends UploadComponent {
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      return {
        ...(nextProps.value || {}),
      };
    }
    return null;
  }
  constructor() {
    super();
    this.state = {
      fileUrl: '',
    };
    this.cropperRef = React.createRef(null);
  }

  componentDidMount() {
    const action = this.props.action ? `${this.action}${this.props.action}` : this.action;
    this.uploadOptions = {
      ...this.uploadOptions,
      action: action,
      listType: 'picture-card',
      showUploadList: false,
      onChange: this.handleChange,
      beforeUpload: this.beforeUploadImg,
    };
  }

  beforeUploadImg = (file) => {
    //如果需要在上传前剪裁
    if (this.props.isCropper) {
      const isOK = this.beforeUpload(file);
      if (isOK) {
        this.getBase64(file, (imageUrl) => {
          this.cropper(imageUrl, file);
        });
      }

      return false;
    } else {
      this.beforeUpload(file);
    }
  };

  beforeUpload = (file) => {
    const isImg =
      file.type === 'image/png' ||
      file.type === 'image/svg+xml' ||
      file.type === 'image/jpeg' ||
      file.type === 'image/jpg';
    if (!isImg) {
      message.error('请上传PNG/JPG/JPEG/SVG格式的图片!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      message.error('不能超过5MB!');
      return false;
    }
    return isImg && isLt2M;
  };

  // 剪裁
  cropper = (baseUrl, file) => {
    const index = Modal.open({
      title: '裁剪图片',
      content: <div style={{ marginBottom: '30px' }}>{this.renderCropper(baseUrl)}</div>,
      okTxt: '保存',
      cancelTxt: '取消',
      isOkBtn: true,
      isCancelBtn: true,
      width: 800,
      maskClosable: true,
      ok: () => {
        this.cropSubmit(file, index);
      },
      cancel: () => {
        Modal.close(index);
      },
    });
  };

  cropSubmit = (file, index) => {
    this.cropperRef.current.getCroppedCanvas({ width: this.props.r_w, height: this.props.r_h }).toBlob((blob) => {
      const formData = new FormData();
      console.log(file.type);
      let extend = '';
      switch (file.type) {
        case 'image/svg+xml':
          extend = 'svg';
          break;
        case 'image/png':
          extend = 'png';
          break;
        case 'image/jpeg':
          extend = 'jpeg';
          break;
        case 'image/jpg':
          extend = 'jpg';
          break;
        default:
          break;
      }
      if (!extend) {
        message.warning('请上传PNG/JPG/JPEG/SVG格式的图片!');
        return;
      }
      formData.append('file', blob, 'a.' + extend);
      services.common.uploadImg(formData).then((res) => {
        if (res.code === 1) {
          message.error(res.msg);
          return;
        }
        this.setState({ fileUrl: res.file_id });
        this.inputHandleChange({ fileUrl: res.file_id });
        Modal.close(index);
      });
    });
  };

  renderCropper = (url) => {
    return (
      <Cropper
        ref={this.cropperRef}
        src={url}
        style={{ height: 500, width: '100%' }}
        aspectRatio={this.props.aspectRatio}
        guides={false}
      />
    );
  };

  handleChange = (info) => {
    this.uploadChange(info).then((url) => {
      this.setState({ fileUrl: url });
      this.inputHandleChange({ fileUrl: url });
    });
  };
  inputHandleChange(value) {
    this.triggerChange(value);
  }
  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(Object.assign({}, this.state, changedValue));
    }
  };
  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className='ant-upload-text'>上传缩略图</div>
      </div>
    );
    if (this.props.uploadOptions) {
      this.uploadOptions = {
        ...this.uploadOptions,
        ...this.props.uploadOptions,
      };
    }
    const imageUrl = this.state.fileUrl ? `${APIUrl}/file/view?file_id=${this.state.fileUrl}` : '';
    return (
      <div>
        <Upload {...this.uploadOptions}>
          {imageUrl ? <img src={imageUrl} style={{ width: 80 }} alt='preview_img' /> : uploadButton}
        </Upload>
        <input type='hidden' value={this.state.fileUrl} onChange={this.inputHandleChange} />
      </div>
    );
  }
}

export default PreviewUploadComponent;
